<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import { useMouseInElement } from '@vueuse/core'

const props = withDefaults(
  defineProps<{
    imagesList?: string[]
  }>(),
  {
    imagesList: () => []
  }
)

const currentIndex = ref(0)

const changeIndex = (index: number) => {
  currentIndex.value = index
}

const target = ref(null)
const show = ref(false)
const layerTop = ref(0)
const layerLeft = ref(0)
const { elementX, elementY, isOutside } = useMouseInElement(target)

watchEffect(() => {
  if (isOutside.value) {
    show.value = false
    return
  }
  if (elementX.value < 100) {
    layerLeft.value = 0
  } else if (elementX.value > 300) {
    layerLeft.value = 200
  } else {
    layerLeft.value = elementX.value - 100
  }
  if (elementY.value < 100) {
    layerTop.value = 0
  } else if (elementY.value > 300) {
    layerTop.value = 200
  } else {
    layerTop.value = elementY.value - 100
  }
  show.value = true
})
</script>

<template>
  <div class="goods-image">
    <div
      class="large"
      v-if="show"
      :style="{
        backgroundImage: `url(${imagesList[currentIndex]})`,
        backgroundPosition: `${-layerLeft * 2}px ${-layerTop * 2}px`
      }"
    ></div>
    <div class="middle" ref="target">
      <img :src="imagesList[currentIndex]" />
      <div
        class="layer"
        v-if="show"
        :style="{ top: layerTop + 'px', left: layerLeft + 'px' }"
      ></div>
    </div>
    <ul class="small">
      <li
        v-for="(item, index) in imagesList"
        @mouseenter="changeIndex(index)"
        :class="{ active: index === currentIndex }"
      >
        <img :src="item" />
      </li>
    </ul>
  </div>
</template>

<style lang="less" scoped>
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    // box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @themeColor;
      }
    }
  }
}
</style>
